// Package drivers mysql db drives
package drivers

import (
	"database/sql"
	"fmt"
	"ginmin/configs"
	_ "github.com/go-sql-driver/mysql"
	"strconv"
	"time"
)

var MysqlDb *sql.DB  // db pool instance
var MysqlDbErr error // db err instance

func init() {
	// get db config
	dbConfig := configs.GetDbConfig()
	if dbConfig["DB_HOST"] != "" {
		dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s",
			dbConfig["DB_USER"],
			dbConfig["DB_PWD"],
			dbConfig["DB_HOST"],
			dbConfig["DB_PORT"],
			dbConfig["DB_NAME"],
			dbConfig["DB_CHARSET"],
		)

		MysqlDb, MysqlDbErr = sql.Open("mysql", dbDSN)

		if MysqlDbErr != nil {
			panic("database data source name error: " + MysqlDbErr.Error())
		}

		dbMaxOpenConns, _ := strconv.Atoi(dbConfig["DB_MAX_OPEN_CONNS"])
		MysqlDb.SetMaxOpenConns(dbMaxOpenConns)

		dbMaxIdleConns, _ := strconv.Atoi(dbConfig["DB_MAX_IDLE_CONNS"])
		MysqlDb.SetMaxIdleConns(dbMaxIdleConns)

		dbMaxLifetimeConns, _ := strconv.Atoi(dbConfig["DB_MAX_LIFETIME_CONNS"])
		MysqlDb.SetConnMaxLifetime(time.Duration(dbMaxLifetimeConns))

		if MysqlDbErr = MysqlDb.Ping(); nil != MysqlDbErr {
			panic("database connect failed: " + MysqlDbErr.Error())
		}
	}
}
